#coding:utf-8
import tkinter as tk
from tkinter import scrolledtext, messagebox
import json
import tencentcloud.common.exception.tencent_cloud_sdk_exception as exce
from tencentcloud.common.profile.http_profile import HttpProfile
from tencentcloud.common.profile.client_profile import ClientProfile
from tencentcloud.common.credential import Credential
from tencentcloud.hunyuan.v20230901 import hunyuan_client, models


class ChatBotApp:
    def __init__(self, root):
        self.root = root
        self.root.title("老张聊天机器人")
        self.root.geometry("500x650")

        # 初始化聊天记录
        self.chat_history = [
            {
                "Role": "system",
                "Content": "请以老张身份进行对话，要求回答要像微信聊天、随意自然，单次回答不能太长简短，绝对限制在60字以内！.......具体的内容自己填写"},

        ]

        # 创建界面组件
        self.create_widgets()

        # 初始化腾讯云客户端
        self.init_client()

    def init_client(self):
        """初始化腾讯云API客户端"""
        try:
            # 混淆后的腾讯云API密钥
            obfuscated_secret_id = '*****************'
            obfuscated_secret_key = '*******************'

            # 解密密钥  非必须项
            SECRET_ID = self.get_decrypted_key(obfuscated_secret_id)
            SECRET_KEY = self.get_decrypted_key(obfuscated_secret_key)

            # 初始化凭据
            credential = Credential(SECRET_ID, SECRET_KEY)

            # 创建HTTP配置
            http_profile = HttpProfile()
            http_profile.req_method = "POST"
            http_profile.req_timeout = 30
            http_profile.endpoint = "hunyuan.tencentcloudapi.com"

            # 创建客户端配置
            client_profile = ClientProfile()
            client_profile.http_profile = http_profile

            # 创建客户端
            self.client = hunyuan_client.HunyuanClient(credential, "", client_profile)

        except Exception as e:
            messagebox.showerror("错误", f"初始化API客户端失败: {str(e)}")

    def get_decrypted_key(self, obfuscated_key):
        """解密混淆后的密钥"""

        key = obfuscated_key.replace('@#@', 'a').replace('$%$', 't').replace('^&^', 'Z')
        return key[::-1]

    def create_widgets(self):
        """创建界面组件"""
        # 聊天记录显示区域
        self.chat_display = scrolledtext.ScrolledText(
            self.root,
            wrap=tk.WORD,
            width=60,
            height=30,
            bg="#1e1e1e",
            fg="#ffffff",
            insertbackground="#ffffff",
            font=("Consolas", 12),
            state='disabled'
        )
        self.chat_display.pack(pady=10, padx=10)

        # 用户输入区域
        self.user_input_frame = tk.Frame(self.root, bg="#1e1e1e")
        self.user_input_frame.pack(fill=tk.X, padx=8, pady=5)

        self.input_entry = tk.Entry(
            self.user_input_frame,
            width=45,
            bg="#333333",
            fg="#ffffff",
            insertbackground="#ffffff",
            font=("Consolas", 12),
            borderwidth=2,
            relief="flat"
        )
        self.input_entry.pack(side=tk.LEFT, expand=True, fill=tk.X)
        self.input_entry.bind("<Return>", lambda event: self.send_message())

        # 发送按钮
        self.send_button = tk.Button(
            self.user_input_frame,
            text="Send",
            command=self.send_message,
            bg="#222222",
            fg="#ffffff",
            font=("Consolas", 12),
            borderwidth=0,
            relief="flat",
            activebackground="#333333",
            activeforeground="#ffffff"
        )
        self.send_button.pack(side=tk.RIGHT, padx=(5, 0))

    def send_message(self):
        """发送用户消息并获取回复"""
        user_message = self.input_entry.get().strip()
        if not user_message:
            return

        # 添加用户消息到聊天记录
        self.chat_history.append({
            "Role": "user",
            "Content": user_message
        })

        # 显示用户消息
        self.display_message("你", user_message)
        self.input_entry.delete(0, tk.END)

        # 获取机器人回复
        self.get_bot_response()

    def get_bot_response(self):
        """获取机器人回复"""
        try:
            # 创建请求对象
            req = models.ChatCompletionsRequest()

            # 设置请求参数
            params = {
                "TopP": 1,
                "Temperature": 0.7,
                "Model": "hunyuan-standard",
                "Stream": False,
                "Messages": self.chat_history
            }

            # 将参数编码为JSON字符串
            req.from_json_string(json.dumps(params))

            # 发送请求
            resp = self.client.ChatCompletions(req)

            # 解析响应
            response_data = json.loads(resp.to_json_string())
            bot_response = response_data['Choices'][0]['Message']['Content']

            # 添加机器人回复到聊天记录
            self.chat_history.append({
                "Role": "assistant",
                "Content": bot_response
            })

            # 显示机器人回复
            self.display_message("老张", bot_response)

        except exce.TencentCloudSDKException as err:
            messagebox.showerror("API错误", str(err))
        except Exception as e:
            messagebox.showerror("错误", f"获取回复时出错: {str(e)}")

    def display_message(self, sender, message):
        """在聊天区域显示消息"""
        self.chat_display.config(state='normal')
        self.chat_display.insert(tk.END, f"{sender}: {message}\n\n")
        self.chat_display.config(state='disabled')
        self.chat_display.see(tk.END)


if __name__ == "__main__":
    root = tk.Tk()
    app = ChatBotApp(root)
    root.mainloop()